﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using JXT.PrimaryKey.Batman.WcfService.Interfaces;

namespace JXT.PrimaryKey.Batman.WcfService
{
    public class ServiceFactory : IServiceFactory
    {
        public Uri ServiceUrl { get; private set; }

        public Binding ServiceBinding { get; private set; }

        public ServiceFactory(Uri serviceUrl)
        {
            ServiceUrl = serviceUrl;
            var httpBinding = new BasicHttpBinding();
            httpBinding.MaxReceivedMessageSize = Int32.MaxValue;
            httpBinding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
            httpBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            ServiceBinding = httpBinding;
        }

        private IUser _userService;
        private ChannelFactory<IUser> _userServiceFactory;

        public IUser UserService
        {
            get
            {
                if (_userService == null)
                {
                    _userServiceFactory = new ChannelFactory<IUser>(ServiceBinding, String.Format("{0}{1}", ServiceUrl, "user.svc"));
                    _userService = _userServiceFactory.CreateChannel();
                }
                return _userService;
            }
        }
     
        public void Dispose()
        {
            if (_userServiceFactory != null)
                disposeChannelFactory(_userServiceFactory);
        }

        private static void disposeChannelFactory(ChannelFactory channelFactory)
        {
            try
            {
                channelFactory.Close();
            }
            catch
            {
                channelFactory.Abort();
            }
        }


        
    }
}
